package org.xurui.bsj.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.bsj.protocol.cache.ConcurrentMapCache;
import org.xurui.bsj.protocol.command.CmdCodec;
import org.xurui.bsj.protocol.enums.CommandEnum;
import org.xurui.bsj.protocol.msg.BsjMessage;
import org.xurui.bsj.protocol.msg.BsjMessageBuilder;
import org.xurui.bsj.protocol.utils.ArrayUtils;
import org.xurui.bsj.protocol.utils.BinaryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4.2.17. 设置通话时长（暂不使用）
 */
@Slf4j
public class CmdCodec_SET_CALL_DURATION implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.SET_CALL_DURATION.name().equals(cmd);
    }

    @Override
    public List<DeviceMessage> parsePayload(BsjMessage payload, FromDeviceMessageContext context) {
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000, SET_CALL_DURATION,2,20180528111820,1,0]
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        report.setDeviceId(payload.getHeader().getDeviceNo());
        report.setFunctionId(payload.getHeader().getCmd());
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(payload.getHeader().getOrderNo());
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = payload.getHeader().getOrderNo();
        }
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        String tempBody = payload.getTempBody();
        String[] tempBodyArr = tempBody.split("@");
        //properties.put("header", FastBeanCopier.copy(payload.getHeader(), HashMap::new));
        properties.put("header", payload.getHeader().toMap());
        //应答状态(0=设置成功;1=设置异常;)
        properties.put("responseStatus", ArrayUtils.getStrByIndex(tempBodyArr,0));
        report.setOutput(properties);
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000, SET_CALL_DURATION,1,20180528111820,2,1@110@W@2@1]
        /**
         * 报文体格式： 新增/删除
         *            @时长(分钟)
         *            @周期
         *            @限制类型
         *            @限制号码
         *            1.第一位：1 设置 0 删除
         *            第二位 ：周期限制通话时长分钟 999>取值范围>0
         *            第三位：M 每月(每月时表示自然月) D 每天 W 每周
         *            第四位：1 限制呼入 2 限制呼出 3 限制呼入呼出
         *            第五位：1，限制除 SOS 外所有号码，2 限制所有号码 3，限制白名单号码 4 只限制 3 个亲情号码 1@110@W@2@1 设备默认不限制。
         */
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String  callOpt="";
            if(paramsMap.get("callOpt")!=null && !paramsMap.get("callOpt").equals("")) {
                callOpt=paramsMap.get("callOpt").toString();
            }

            String duration="";
            if(paramsMap.get("duration")!=null && !paramsMap.get("duration").equals("")) {
                duration=paramsMap.get("duration").toString();
            }
            String  cycle="";
            if(paramsMap.get("cycle")!=null && !paramsMap.get("cycle").equals("")) {
                cycle=paramsMap.get("cycle").toString();
            }

            String callType="";
            if(paramsMap.get("callType")!=null && !paramsMap.get("callType").equals("")) {
                callType=paramsMap.get("callType").toString();
            }

            String restrict="";
            if(paramsMap.get("restrict")!=null && !paramsMap.get("restrict").equals("")) {
                restrict=paramsMap.get("restrict").toString();
            }


            StringBuffer sb = new StringBuffer();
            sb.append(callOpt);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(duration);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(cycle);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(callType);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(restrict);

            return BsjMessageBuilder.create().buildBsjFunctionInvoickMessage(m,sb.toString());
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.SET_CALL_DURATION.name(),message);
            }
            return null;
        }

    }
}
